<template>
  <div class="warp">
    <a-affix :offset-top="0">
      <div class="page-top">
        <span style="margin-left: 20px"></span>
        <span>代码生成器v1.1.201</span>
        <div>
          <a-button
            type="link"
            style="color: #fff; font-weight: bold; font-size: 18px"
            @click="protogenesis"
          >
            vue+antdv/element原生代码生成器
          </a-button>
        </div>
      </div>
    </a-affix>
    <div id="export">
      <a-button type="link" @click="visible = true">导入列表数据</a-button>
      <!-- <a-button type="link" @click="exportJS">导出JS</a-button> -->
      <a-button type="link" @click="checkCode">查看代码</a-button>
      <!-- <a-button type="link" v-clipboard:copy="formcode">复制</a-button> -->
      <!-- <a-button type="link" @click="singleForm">生成单个from表单</a-button> -->
    </div>

    <!-- 基础区域 -->
    <div style="padding: 15px" id="basics">
      <Basics
        v-show="show"
        :form="form"
        @FieldSet="FieldSet"
        @RemoveField="RemoveField"
        @FieldNames="FieldNames"
        @FieldsType="FieldsType"
      />

      <!-- crud设置 -->
      <a-card title="crud设置" v-show="show" id="settings">
        <a-form-model layout="inline">
          <a-form-model-item
            :label="item.label"
            v-for="(item, index) in config"
            :key="index"
          >
            <a-switch v-model="item.status">
              <a-icon slot="checkedChildren" type="check" />
              <a-icon slot="unCheckedChildren" type="close" />
            </a-switch>
          </a-form-model-item>
          <a-form-model-item label="批量删除">
            <a-switch v-model="config[3].batch">
              <a-icon slot="checkedChildren" type="check" />
              <a-icon slot="unCheckedChildren" type="close" />
            </a-switch>
          </a-form-model-item>
        </a-form-model>
      </a-card>

      <!-- 增删改查 -->

      <CRUD :config="config" v-show="show" id="allocation" />

      <!-- 接口 -->

      <Api :ApiData="ApiData" v-show="show" id="api" />
    </div>

    <!-------------------------------------------- 导入列表数据弹窗区域start -------------------------------------------->
    <a-modal
      :maskClosable="false"
      v-model="visible"
      title="导入列表数据"
      @ok="interfaceOk"
    >
      <a-textarea
        v-model="interfaceData"
        placeholder="请输入或者粘贴要导入JSON数据，如:{'name':'xxxx'}"
        allow-clear
        :rows="20"
        @change="interfaceChange"
      />
    </a-modal>
    <!-------------------------------------------- 导入列表数据弹窗区域end -------------------------------------------->
    <a-modal
      @cancel="preview = '1'"
      :maskClosable="true"
      v-model="checkVisible"
      title="查看代码"
      :width="900"
    >
      <template slot="footer">
        <a-button v-if="preview === '1'" v-clipboard:copy="formcode">
          复制FormJson.js代码
        </a-button>
        <a-button v-if="preview === '2'" v-clipboard:copy="vueCode">
          复制index.vue代码
        </a-button>
        <a-button v-if="preview === '3'" v-clipboard:copy="apiCode">
          复制api.js代码
        </a-button>
        <a-button
          icon="download"
          @click="exportCode('FormJson', formcode, '.js')"
          v-if="preview === '1'"
        >
          下载FormJson.js代码
        </a-button>
        <a-button
          icon="download"
          @click="exportCode('index', vueCode, '.vue')"
          v-if="preview === '2'"
        >
          下载index.vue代码
        </a-button>
        <a-button
          icon="download"
          @click="exportCode('api', apiCode, '.js')"
          v-if="preview === '3'"
        >
          下载api.js代码
        </a-button>
        <a-button @click="checkVisible = false">关闭</a-button>
      </template>
      <a-tabs v-model="preview" tab-position="left">
        <a-tab-pane key="1" tab="FormJson.js">
          <codemirror
            :options="{
              mode: 'javascript',
              extraKeys: { 'Ctrl-Space': 'autocomplete' }
            }"
            :value="formcode"
          ></codemirror>
        </a-tab-pane>
        <a-tab-pane key="2" tab="index.vue">
          <codemirror
            :options="{
              mode: 'vue',
              extraKeys: { 'Ctrl-Space': 'autocomplete' }
            }"
            :value="vueCode"
          ></codemirror>
        </a-tab-pane>
        <a-tab-pane
          :options="{
            mode: 'javascript',
            extraKeys: { 'Ctrl-Space': 'autocomplete' }
          }"
          key="3"
          tab="api.js"
        >
          <codemirror :value="apiCode"></codemirror>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
    <a-drawer
      :width="500"
      title="字段设置"
      placement="right"
      :visible="settingsVisible"
      :after-visible-change="afterVisibleChange"
      @close="onClose(form[key].model, form[key].wrapper.label)"
    >
      <FieldSet
        :form="form"
        :FieldKey="key"
        @FieldsType="FieldsType"
        @FieldNames="FieldNames"
      />
      <div class="bottom_btn">
        <a-button
          type="primary"
          @click="onClose(form[key].model, form[key].wrapper.label)"
        >
          关 闭
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import * as components from "@/components";
import * as vueCodemirrorLite from "vue-codemirror-lite";
require("codemirror/mode/javascript/javascript");
require("codemirror/mode/vue/vue");
require("codemirror/addon/hint/show-hint.js");
require("codemirror/addon/hint/show-hint.css");
require("codemirror/addon/hint/javascript-hint.js");
import {
  packageApi,
  exportData,
  packageFormJs,
  packageVue
} from "@/utils/publicMethod";
import { FieldsType } from "@/utils/FieldsType";
export default {
  components: {
    codemirror: vueCodemirrorLite.codemirror,
    Basics: components.Basics,
    CRUD: components.CRUD,
    FieldSet: components.FieldSet,
    Api: components.Api
  },
  data() {
    return {
      preview: "1",

      show: false,
      formcode: "",
      key: -1,
      settingsVisible: false,
      visible: false,
      interfaceData: "",
      form: [],
      vueCode: null,
      apiCode: null,
      config: [
        // 增
        {
          mark: 1,
          status: false,
          label: "新增",
          value: "create",
          labelCol: 4,
          wrapperCol: 20,
          checkboxData: []
        },
        // 改
        {
          mark: 2,
          status: false,
          label: "修改",
          value: "update",
          labelCol: 4,
          wrapperCol: 20,
          checkboxData: []
        },
        // 搜索
        {
          mark: 3,
          status: false,
          label: "搜索",
          value: "search",
          labelCol: 4,
          wrapperCol: 20,
          checkboxData: []
        },
        //表格
        {
          mark: 4,
          batch: false,
          status: false,
          label: "列表",
          value: "table",
          rowKey: "id",
          checkboxData: []
        }
      ],

      checkVisible: false,
      ApiData: {
        retrieveReq: "",
        createReq: "",
        updateReq: "",
        deleteReq: "",
        deleteBatchReq: "",
        detailReq: ""
      }
    };
  },

  created() {
    this.form = [];
    // this.interfaceData = JSON.stringify({
    //   bankName: "青岛银行",
    //   bankNo: "172381239812",
    //   gmtCreate: 1599018599000,
    //   gmtModified: 1599025816000,
    //   id: "CFE85521205C40D1B2F66FEDF55F1D60",
    //   idcard: "370983198706132428",
    //   idcardBack:
    //     "https://res.lanxiang.co/test/9d6ce5af-fc5b-4cf4-9ec6-d0073db4f6de/5f039250-5392-48c3-909e-58bebd857616.png",
    //   idcardFront:
    //     "https://res.lanxiang.co/test/5972540e-8d66-4702-a13b-bfb2777d18c6/ffa39d48-579a-4343-bf70-7f80b14c3238.png",
    //   name: "刘景照渠道商",
    //   phone: "18366626195"
    // });
    // this.interfaceOk();
  },
  methods: {
    protogenesis() {
      this.$router.push({ name: "VueAntdv" });
    },
    RemoveField(index) {
      this.config.forEach(element => {
        element.checkboxData.forEach((e, i) => {
          if (e.value == this.form[index].wrapper.label) {
            element.checkboxData.splice(i, 1);
          }
        });
      });
      this.form.splice(index, 1);
      this.$message.success("删除字段成功!");
    },
    FieldNames(el, value, index) {
      const type = this.form[index].type;
      const newLocal =
        type === "input" ||
        type === "textarea" ||
        type === "number" ||
        type === "autoComplete";
      if (newLocal) {
        this.form[index].customize.placeholder = `请输入${el.target.value}`;
        this.form[
          index
        ].decorator.rules[0].message = `请输入${el.target.value}`;
      }
      if (type === "date" || type === "select") {
        this.form[index].customize.placeholder = `请选择${el.target.value}`;
        this.form[
          index
        ].decorator.rules[0].message = `请选择${el.target.value}`;
      }

      this.config.forEach(element => {
        element.checkboxData.forEach(e => {
          if (e.value == value) {
            this.$nextTick(() => {
              e.label = el.target.value;
            });
          }
        });
      });
    },

    // 查看代码
    checkCode() {
      this.preview = "1";
      this.apiCode = packageApi(this.ApiData);
      this.formcode = packageFormJs(this.config, this.form);
      this.vueCode = packageVue(this.config);
      this.checkVisible = true;
    },
    // 单个表单
    singleForm() {},
    // 字段下拉变化
    FieldsType(value, key, model, label) {
      this.$set(this.form, key, FieldsType(value, model, label));
    },
    // 导出JS
    exportCode(name, code, suffix) {
      exportData(name, code, suffix);
    },

    // eslint-disable-next-line no-unused-vars
    afterVisibleChange(val) {},
    showDrawer() {
      this.visible = true;
    },
    onClose(value, label) {
      this.config.forEach(element => {
        element.checkboxData.forEach(e => {
          if (e.value == value) {
            e.label = label;
          }
        });
      });
      this.settingsVisible = false;
    },

    FieldSet(key) {
      this.key = key;

      this.settingsVisible = true;
    },
    // 获取接口数据
    interfaceOk() {
      try {
        this.form = [];

        let _interfaceData = JSON.parse(this.interfaceData);

        let arr = [];
        for (const key in _interfaceData) {
          arr.push({
            label: key,
            value: key,
            checkbox: false,
            disabled: false
          });
          this.form.push({
            model: key,
            type: "input",

            wrapper: {
              label: key
            },

            customize: {
              placeholder: `请输入${key}`,
              allowClear: true
            },
            decorator: {
              initialValue: "",
              rules: [
                {
                  required: false,
                  message: `请输入${key}`
                }
              ]
            },
            extend: {}
          });
        }
        this.config.forEach(element => {
          element.checkboxData = JSON.parse(JSON.stringify(arr));
        });

        this.visible = false;
        this.show = true;
        this.$message.success("导入成功");
      } catch (error) {
        console.log("1debug log --> ", error);

        this.show = false;
      }
    },
    // 导入列表数据
    interfaceChange() {}
  }
};
</script>

<style lang="scss" scoped>
.warp {
  width: 100%;
}
.page-top {
  width: 100%;
  height: 56px;
  text-align: center;
  background: #13c2c2;
  color: #fff;
  line-height: 56px;
  font-size: 18px;
  font-weight: 700;
  display: flex;
  justify-content: space-between;
}

.deleteIcon {
  margin: 5px;
  cursor: pointer;
  font-size: 20px;
  background: rgb(255, 233, 233);
  color: rgb(255, 34, 34);
  padding: 4px;
  border-radius: 50%;
}
.deleteIcon:hover {
  color: rgb(255, 255, 255);
  background: rgb(255, 34, 34);
}
.bottom_btn {
  position: "absolute";
  right: 0;
  bottom: 0;
  width: "100%";
  border-top: "1px solid #e9e9e9";
  padding: "10px 16px";
  background: "#fff";
  text-align: "right";
  z-index: 1;
}
</style>
